package mysql

import (
	"gorm.io/gorm"
	"practice-one/userrpc/userrpc"
)

type Goods struct {
	gorm.Model
	UserId    int64   `gorm:"type:int(11);not null;comment:用户id"`
	Title     string  `gorm:"Type:varchar(50);not null;comment:标题"`
	GoodsType string  `gorm:"Type:varchar(50);not null;comment:分类"`
	Price     float32 `gorm:"type:decimal(10,2);not null;comment:价格"`
	Content   string  `gorm:"Type:varchar(100);not null;comment:描述"`
}

func (g *Goods) GoosAdd(db *gorm.DB) error {
	return db.Debug().Create(g).Error
}

func (g *Goods) FindGoodsById(db *gorm.DB, id int64) error {
	return db.Debug().Where("id =?", id).First(g).Error
}

/*
SELECT

	users.nick_name,
	users.head_image,
	goods.id goods_id,
	goods.content,
	goods.goods_type,
	goods.price,
	goods.title

FROM

	goods
	LEFT JOIN users ON goods.user_id = users.id
*/
func GoodsList(db *gorm.DB, in *userrpc.GoodsListRequest) []*userrpc.GoodsList {
	var list []*userrpc.GoodsList
	tx := db.Debug().Model(&Goods{}).
		Select(
			"users.nick_name",
			"users.head_image",
			"goods.id goods_id",
			"goods.content",
			"goods.goods_type",
			"goods.price",
			"goods.title",
		).
		Joins("LEFT JOIN users ON goods.user_id = users.id").
		Order("goods.created_at desc").
		Scopes(Paginate(int(in.Page), int(in.Size)))
	if in.GoodsType != "" {
		tx = tx.Where("goods_type like ?", "%"+in.GoodsType+"%")
	}
	if in.Title != "" {
		tx = tx.Where("title like ?", "%"+in.Title+"%")
	}
	tx = tx.Find(&list)
	return list
}
